package com.ziyueyuwen.xiniao.service.report.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.ziyueyuwen.xiniao.bean.ZyClassLessonInfo;
import com.ziyueyuwen.xiniao.bean.ZyClassLessonTransfer;
import com.ziyueyuwen.xiniao.bean.ZyClassLessonUser;
import com.ziyueyuwen.xiniao.bean.ZyUser;
import com.ziyueyuwen.xiniao.bean.homework.HomeworkMarkData;
import com.ziyueyuwen.xiniao.bean.homework.ZyHomeworkRecordDO;
import com.ziyueyuwen.xiniao.bean.report.StudentLessonReportVO;
import com.ziyueyuwen.xiniao.bean.report.ZyStudentLessonReport;
import com.ziyueyuwen.xiniao.bean.subscription.ZySubscriptionMsgDO;
import com.ziyueyuwen.xiniao.bean.vo.ZyClassLessonUserVO;
import com.ziyueyuwen.xiniao.bean.vo.ZyLessonVO;
import com.ziyueyuwen.xiniao.dao.ZyClassLessonInfoMapper;
import com.ziyueyuwen.xiniao.dao.ZySubscriptionMsgMapper;
import com.ziyueyuwen.xiniao.enums.HomeworkStatusEnum;
import com.ziyueyuwen.xiniao.enums.ReportInOutEnum;
import com.ziyueyuwen.xiniao.service.*;
import com.ziyueyuwen.xiniao.service.baseservice.report.ReportBaseService;
import com.ziyueyuwen.xiniao.service.report.ReportService;
import com.ziyueyuwen.xiniao.thirdpart.bean.msg.DingTalkLinkBean;
import com.ziyueyuwen.xiniao.thirdpart.util.DingTalkConstUtil;
import com.ziyueyuwen.xiniao.thirdpart.util.DingTalkMessageUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.ziyueyuwen.xiniao.util.ConstUtil.SYS_CONFIG_DATA;

/**
 * @author wancheng  on 2019/3/15.
 */
@Service
public class ReportServiceImpl implements ReportService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final String IMAGE_LOGO_URL = "http://ziyue-xn.oss-cn-beijing.aliyuncs.com/common/kongziwx.png";
    ///writeFeedback/courseId/lessonNum/lessonId/13120335328
    private final String LESSON_REPORT_URL = SYS_CONFIG_DATA.getDomainName() + "/writeFeedback/%s/%s/%s/%s";

    @Autowired
    ReportBaseService reportBaseService;
    @Autowired
    LessonService lessonService;
    @Autowired
    ClassService classService;
    @Autowired
    TransferStudentService transferStudentService;
    @Autowired
    HomeworkRecordService homeworkRecordService;
    @Autowired
    ZySubscriptionMsgMapper zySubscriptionMsgMapper;
    @Autowired
    ZyClassLessonInfoMapper zyClassLessonInfoMapper;
    @Autowired
    LessonUserService lessonUserService;
    @Autowired
    UserService userService;
    @Autowired
    ThirdPartService thirdPartService;
    @Autowired
    WxMessageService wxMessageService;

    @Override
    public List<StudentLessonReportVO> produceLessonReport(Integer lessonId) {

        List<ZyClassLessonUserVO> students = lessonUserService.getStudent(lessonId);
        students.forEach(
                s -> {
                    getReportMsgWhileIsNUllToSave(s.getUserAccount(), lessonId);
                }
        );
        return reportBaseService.getStudentLessonReport(lessonId);
    }

    @Override
    public ZyStudentLessonReport getReportMsgWhileIsNUllToSave(String studentAccount, Integer lessonId) {
        ZyStudentLessonReport report = reportBaseService.getByReport(studentAccount, lessonId);
        if (report != null) {
            return report;
        }
        ZyLessonVO zyLessonVO = lessonService.getClassAndCourseByLessonId(lessonId);
        report = new ZyStudentLessonReport();
        report.setLessonId(lessonId);
        report.setCourseId(zyLessonVO.getCourse().getId());
        report.setLessonIndex(zyLessonVO.getLessonIndex());
        report.setStudentAccount(studentAccount);
        report.setScore(0);
        report.setAward(0);
        report.setPreview(false);
        report.setHomework(HomeworkStatusEnum.NOT_START);
        report.setExpansion(false);
        report.setSummarize(false);
        report.setReplay(false);
        report.setIfHasNote(false);
        report.setAttendance(ReportInOutEnum.ABSENT);
        //学生可能是插班生,所以课节和所属班级有可能不同
        ZyClassLessonTransfer transfer = transferStudentService.getTransferStudent(lessonId, studentAccount);
        if (transfer != null) {
            report.setClassId(transfer.getClassId());
        } else {
            report.setClassId(zyLessonVO.getClassInfo().getId());
        }
        report.setCreateTime(new Date());
        reportBaseService.saveReturnPreKey(report);
        return report;
    }

    @Override
    public void updateReportScore(String studentAccount, Integer lessonId) {
        try {
            ZyStudentLessonReport report = getReportMsgWhileIsNUllToSave(studentAccount, lessonId);
            ZyStudentLessonReport update = new ZyStudentLessonReport();
            update.setId(report.getId());
            ZyHomeworkRecordDO sh = homeworkRecordService.getByStudentIdAndLessonId(studentAccount, lessonId);
            if (sh != null) {
                HomeworkMarkData h = sh.getMarkInfo();
                if (h != null) {
                    JSONObject sj = h.getScoreObj();
                    Integer subjective = sj.getInteger("subjectiveScoreStudent") == null ? 0 : sj.getInteger("subjectiveScoreStudent");
                    Integer objective = sj.getInteger("objectiveScoreStudent") == null ? 0 : sj.getInteger("objectiveScoreStudent");
                    update.setScore(subjective + objective);
                    update.setHomework(HomeworkStatusEnum.CORRECTED);
                }
            }
            updateByPreKey(update);
            if (report.getAward() == 0) {
                //补充老数据
                updateAwardForOldData(report.getLessonId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateAwardForOldData(Integer lessonId) {
        try {
            ZyClassLessonInfo lessonInfo = zyClassLessonInfoMapper.selectByPrimaryKey(lessonId);
            ZySubscriptionMsgDO data = zySubscriptionMsgMapper.getEndMsg(lessonInfo.getEeoLessonId());
            if (data != null) {
                this.updateReportAward(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateReportAward(String studentAccount, Integer lessonId, Integer award) {
        ZyStudentLessonReport report = getReportMsgWhileIsNUllToSave(studentAccount, lessonId);
        ZyStudentLessonReport update = new ZyStudentLessonReport();
        update.setId(report.getId());
        update.setAward(award);
        updateByPreKey(update);
    }

    @Override
    public void updateReportAward(ZySubscriptionMsgDO eeoAwardData) {
        String EEO_CMD_END = "END";
        if (!EEO_CMD_END.equals(eeoAwardData.getCmd())) {
            return;
        }

        try {
            JSONObject data = eeoAwardData.getMsg().getJSONObject("Data");
            JSONObject awardEnd = data.getJSONObject("awardEnd");
            JSONObject inoutEnd = data.getJSONObject("inoutEnd");
            ZyClassLessonInfo lessonInfo = lessonService.getLessonInfoByEeoClassId(eeoAwardData.getEeoClassId());
            if (lessonInfo == null) {
                return;
            }
            List<ZyClassLessonUserVO> students = lessonUserService.getStudent(lessonInfo.getId());
            logger.info("eeo 推送数据,生成课堂报告,lessonId={} ,student={}", lessonInfo.getId(), students.stream().map(ZyClassLessonUserVO::getUserAccount).collect(Collectors.joining(",")));
            for (ZyClassLessonUserVO sv : students) {
                try {
                    ZyUser user = userService.getByAccount(sv.getUserAccount());
                    String uId = user.getuId();
                    ZyStudentLessonReport report = this.getReportMsgWhileIsNUllToSave(sv.getUserAccount(), lessonInfo.getId());
                    Integer award = awardEnd.getJSONObject(uId).getInteger("Total");
                    report.setAward(award);
                    JSONObject inData = inoutEnd.getJSONObject(uId);
                    if (inData == null) {
                        report.setAttendance(ReportInOutEnum.ABSENT);
                    } else {
                        Long inTime = inData.getJSONArray("Details").getJSONObject(0).getLong("Time");
                        if (lessonInfo.getBeginTime().before(new Date(inTime))) {
                            report.setAttendance(ReportInOutEnum.BE_LATE);
                        } else {
                            report.setAttendance(ReportInOutEnum.ON_TIME);
                        }
                    }

                    updateByPreKey(report);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            sendMsgForTeacherFillInReport(lessonInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public Boolean updateByPreKey(ZyStudentLessonReport report) {
        return reportBaseService.updateByPreKey(report);
    }

    @Override
    public List<StudentLessonReportVO> getStudentLessonReport(Integer lessonId) {
        ZyLessonVO lesson = lessonService.getClassAndCourseByLessonId(lessonId);
        if (lesson == null) {
            return null;
        }
        return reportBaseService.getStudentLessonReport(lessonId);
    }

    @Override
    public List<ZyStudentLessonReport> getReport(ZyStudentLessonReport report) {
        return reportBaseService.getByReport(report);
    }

    @Override
    public ZyStudentLessonReport getOne(ZyStudentLessonReport report) {
        return reportBaseService.getOne(report);
    }

    @Override
    public void sendMsgForTeacherFillInReport(Integer lessonId) {
        ZyLessonVO lesson = lessonService.getClassAndCourseByLessonId(lessonId);
        ZyClassLessonUser teacher = lessonUserService.getTeacher(lessonId);
        String dingTalkId = thirdPartService.getDingTalkId(teacher.getUserAccount());
        DingTalkLinkBean talkTextBean = new DingTalkLinkBean();
        talkTextBean.setUserIds(dingTalkId);
        talkTextBean.setAgentId(DingTalkConstUtil.XINIAO_AGENT_ID);
        talkTextBean.setTitle("填写课堂报告");
        ///writeFeedback/courseId/lessonNum/lessonId/13120335328
        talkTextBean.setMessageUrl(String.format(LESSON_REPORT_URL, lesson.getCourse().getId(), lesson.getLessonIndex(), lessonId, teacher.getUserAccount()));
        talkTextBean.setPicUrl(IMAGE_LOGO_URL);
        talkTextBean.setText(String.format("请及时填写课节%s的课堂报告", lesson.getClassLessonName()));
        OapiMessageCorpconversationAsyncsendV2Response response = DingTalkMessageUtil.sendLinkMsg(talkTextBean);
        Boolean ifSendSuccess = false;
        if (response.getErrcode() == 0) {
            ifSendSuccess = true;
        }
        logger.info("发送钉钉消息通知--提醒老师填写课堂报告 lessonId={} teacherAccount={} result={}", lessonId, teacher.getUserAccount(), ifSendSuccess);
    }

    @Override
    public void sendMsgForStudentReport(Integer lessonId, String userAccount) {
        String openId = thirdPartService.getOpenId(userAccount);
        ZyClassLessonUser lessonTeacher = lessonUserService.getTeacher(lessonId);
        ZyUser teacher = userService.getByAccount(lessonTeacher.getUserAccount());
        if (StringUtils.isBlank(openId)) {
            logger.info("发送学生报告失败,openId为空,lessonId={} userAccount={}", lessonId, userAccount);
        }
        wxMessageService.sendLessonReport(openId, lessonId, userAccount, teacher.getUserName());
    }
}
